<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Cache\CacheKey;
use App\Enum\Code;
use App\Exception\BusinessException;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use HyperfExt\Jwt\Jwt;
use HyperfExt\Jwt\Payload;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Logger\LoggerFactory;

class PermissionMiddleware implements MiddlewareInterface
{
    #[Inject]
    protected Jwt $jwt;

    #[Inject]
    protected Redis $redis;
    #[Inject]
    protected LoggerFactory $logger;


    // 作者特有权限
    const authPermission = [

    ];

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $role = Context::get('role');
        if (empty($role) || $role == 'admin') {
            return $handler->handle($request);
        }
        $this->check($request, $role);
        return $handler->handle($request);
    }

    public function check($request, $role)
    {
        $path = $request->getUri()->getPath();
        if ($role == 'user') {
            if (!str_starts_with($path, '/api/web/v1')) {
                throw new BusinessException(Code::PermissionDenied, '无权访问');
            }
        }

        if ($role == 'author') {
            // 作者拥有普通用户权限
            if (!in_array($path, self::authPermission) && !str_starts_with($path, '/api/web/v1')) {
                throw new BusinessException(Code::PermissionDenied, '无权访问');
            }
        }
    }
}
